import * as path from "path";
import * as fs from "fs";
import * as ts from "typescript";
import { log } from "console";

function findEnumReferences(filePath: string, enumName: string) {
  const program = ts.createProgram([filePath], {});
  const checker = program.getTypeChecker();

  const sourceFile = program.getSourceFile(filePath);
  if (!sourceFile) {
    console.error("File not found");
    return;
  }

  let enumReferencesCount: { [key: string]: number } = {};

  function visit(node: ts.Node) {
    if (
      ts.isPropertyAccessExpression(node) &&
      ts.isIdentifier(node.expression)
    ) {
      const symbol = checker.getSymbolAtLocation(node.expression);
      if (symbol && symbol.getName() === enumName) {
        const memberName = node.name.text;
        enumReferencesCount[memberName] =
          (enumReferencesCount[memberName] || 0) + 1;
      }
    }
    ts.forEachChild(node, visit);
  }

  ts.forEachChild(sourceFile, visit);
  console.log(filePath, enumReferencesCount);
  
  return enumReferencesCount;
}

/**
 * 在 vscode 中打开文件 src\components\authorize\Permissions.ts
 *
 * 右键 EnumPermissions 找到所有引用
 *
 * 在 references 中右键 copy all
 *
 * 将内容保存到 references.txt 文件中
 */
function getAllPath() {
  const projectPath = "D:\\ThePiqueLab\\archus-crm-ui";

  // 读取文件内容
  const data = fs.readFileSync("references.txt", "utf8");

  // 使用正则表达式匹配所有以`src/`开头的文件路径
  const regex = /^src\/.*$/gm;
  let matches;
  const fullPaths = [];

  while ((matches = regex.exec(data)) !== null) {
    // 这是必须的，以避免死循环
    if (matches.index === regex.lastIndex) {
      regex.lastIndex++;
    }

    // matches[0] 包含了匹配到的完整文本，即文件路径
    if (matches[0]) {
      // 使用path.join来确保路径在不同操作系统上的正确性
      // path.normalize将会处理任何跨平台的路径问题
      const fullPath = path.normalize(path.join(projectPath, matches[0]));
      fullPaths.push(fullPath);
    }
  }

  // 去重并输出所有的文件路径
  // const uniquePaths = [...new Set(fullPaths)];
  // console.log(uniquePaths.join("\n"));
  return fullPaths;
}

const allPaths = getAllPath();
console.log('path count:', allPaths.length);

let result = {};
allPaths.forEach((p) => {
  // 示例：查找并统计枚举键的引用次数
  const filePath = path.resolve(p);
  const enumName = "EnumPermissions";
  const referencesCount = findEnumReferences(filePath, enumName);
  // console.log(referencesCount);
  Object.entries(referencesCount).forEach(([key, value]) => {
    result[key] = (result[key] || 0) + value;
  })
});

console.log(result);
